package jsu.hx.lost.Service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.util.UUID;
@Slf4j
@Service
public class FileStorageService {
    public String saveImage(MultipartFile file, String subDirectory) throws IOException {
        // 动态子目录（如 "lost_items" 或 "find_items"）
        Path uploadDir = Paths.get("uploads", subDirectory);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }

        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        String fileName = UUID.randomUUID() + "." + extension;

        Path targetPath = uploadDir.resolve(fileName);
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
        }

        return "uploads/" + subDirectory + "/" + fileName;
    }

    public void deleteOldImage(String imagePath) throws IOException {
        if (imagePath == null) return;
        Path filePath = Paths.get(imagePath.replace("/", File.separator));
        Files.deleteIfExists(filePath);
    }
}
